package com.shishuo.cms.filter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.MDC;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import com.shishuo.cms.exception.ViewException;
import com.shishuo.cms.util.HtmlCompressor;
import com.shishuo.cms.util.HttpUtils;

import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ExtendFreeMarkerView  extends FreeMarkerView {
	@Override
    protected void doRender(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        	exposeModelAsRequestAttributes(model, request);
            SimpleHash fmModel = buildTemplateModel(model, request, response);
            if (logger.isDebugEnabled()) {
                logger.debug("Rendering FreeMarker template [" + getUrl() + "] in FreeMarkerView '" + getBeanName() + "'");
            }
            Locale locale = RequestContextUtils.getLocale(request);
            if ("1".equals(model.get("IS_CACHE_HTML"))&&(isNeedHtmlStatic(request))) {
                createHTML(getTemplate(locale), fmModel, request, response);
            } else {
                processTemplate(getTemplate(locale), fmModel, response);
            }
    }
 
    /**
	 * 判断是否需要html静态化处理
	 * @since 2015年3月12日 下午1:48:02
	 * @return
	 */
	private boolean isNeedHtmlStatic( HttpServletRequest request)
	{
		String url=request.getRequestURI();
		if (url.startsWith("/admin")||url.startsWith("/user"))
		{
			return false;
		}
		return true;
	}

	public void createHTML(Template template, SimpleHash model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //站点根目录的绝对路径  
        String basePath = request.getSession().getServletContext().getRealPath("/");
        Locale local=(Locale) request.getSession().getAttribute(
				SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
        local = (null == local) ? LocaleContextHolder.getLocale() : local;
        String requestHTML = "html/"+local.getLanguage()+this.getRequestHTML(request);
        String htmlPath = basePath + requestHTML;
        File htmlFile = new File(htmlPath);
        if (!htmlFile.getParentFile().exists()) {
            htmlFile.getParentFile().mkdirs();
        }
        if (!htmlFile.exists()) {
            htmlFile.createNewFile();
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
            //处理模版    
            template.process(model, out);
            out.flush();
            out.close();
        }
        /* 将请求转发到生成的htm文件 */
        //request.getRequestDispatcher(this.getRequestHTML(request)).forward(request, response);
        response.setContentType("text/html;charset=UTF-8;");
		PrintWriter printWriter = response.getWriter();
		InputStreamReader read = new InputStreamReader(new
				FileInputStream(htmlFile), "UTF-8");
		BufferedReader bufferedReader =
				new BufferedReader(read);
		String lineTxt = null;
		StringBuffer outStringBuffer=new StringBuffer();
		while ((lineTxt = bufferedReader.readLine()) != null)
		{
			outStringBuffer.append(lineTxt);
		}
		printWriter.write(HtmlCompressor.compress(outStringBuffer.toString()));
		read.close();
		printWriter.flush();
		printWriter.close();
		response.flushBuffer();
    }
 
    private String getRequestHTML(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();
        requestURI = requestURI.replaceFirst(contextPath, "");
        requestURI += ".html";
        return requestURI;
    }
}
